package org.jeecg.common.message;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.zhaowl.rsa.util.RsaUtil;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.OkHttpUtil;
import org.jeecg.common.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author jackeyZhao
 * @description 发送短信工具类
 * @date 2023/03/09
 */
@Slf4j
@Component
public class UnicomSmsUtil {

    @Value("${basicplatform.message.url}")
    private String url;

    @Value("${basicplatform.message.userName}")
    private String userName;

    @Value("${basicplatform.message.secretKey}")
    private String secretKey;

    @Value("${basicplatform.message.messageSign}")
    private String messageSign;

    @Value("${basicplatform.message.publicKey}")
    private String publicKey;

    @Autowired
    private RedisUtil redisUtil;

    private String msgTokenCacheKey = "msgToken";

    private Integer msgTokenExpireTime = 30 * 60;


    /**
     * 发送短信
     *
     * @param list
     * @return
     */
    public Boolean sendSms(List<MessageItem> list) {

        //获取token 默认从redis里拿，如果没有就从
        String token;
        if (redisUtil.hasKey(msgTokenCacheKey)) {
            token = redisUtil.get(msgTokenCacheKey).toString();
        } else {
            token = getToken();
            if ("".equals(token)) {
                return false;
            }
            redisUtil.set(msgTokenCacheKey, token);
            redisUtil.expire(msgTokenCacheKey, msgTokenExpireTime);
        }

        list.forEach(messageItem -> {
            messageItem.setMessageSign(messageSign);
        });


        Map<String, String> header = new HashMap<>();
        header.put("Content-Type", "application/json");
        header.put("Accept", "application/json");
        header.put("X-Access-Token", token);
        String sendUrl = url + "/send/sendMessage";
        String result = OkHttpUtil.postJson(sendUrl, header, JSONArray.toJSONString(list));
        log.info("调用短信网关返回结果：\n" + result);
        return !"".equals(result);
    }


    /**
     * 取token
     *
     * @param
     * @return token
     */
    private String getToken() {
        Map<String, String> header = new HashMap<>();
        header.put("Accept", "application/json");
        Map<String, String> sysParams = new HashMap<>();

        sysParams.put("secretKey", secretKey);
        sysParams.put("userName", userName);

        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(date);

        try {
            sysParams.put("sign", Base64.getEncoder().encodeToString(RsaUtil.encryptByPublicKey(publicKey, Base64.getEncoder().encodeToString(time.getBytes()))));
        } catch (Exception e) {
            log.error("加签失败");
        }

        String result = OkHttpUtil.post(url + "/sys/getMsgToken", header, sysParams);
        log.info("【短信】调用短信网关[{}]获得token,返回:[{}],参数[{}]", url + "/sys/getMsgToken", result, sysParams.toString());
        Map<String, Object> hashMap = JSON.parseObject(result, HashMap.class);
        if (result == null || result.trim().equals("")) {
            log.error("调用短信网关[{}]获取token,返回:空", url + "/sys/getMsgToken");
            return "";
        }
        return hashMap.get("result").toString();
    }

}
